package com.eric.utils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Element;

import com.eric.downloader.SeoDownloader;
import com.eric.seo.SeoPage;

/*瑙勫垯锛�
璇ofollow鐨勯潪seo閾炬帴锛岃鍔犱笂nofollow
涓嶈nofollow鐨剆eo閾炬帴锛屼笉鑳藉姞涓妌ofollow*/
public class CheckNofollow extends RobotsTxtParser {
	
	SeoPage seoPage;
	
	public CheckNofollow(SeoPage seoPage) {
		super();
		this.seoPage = seoPage;
	}

	List<String> checkResults = new ArrayList<>();

	public static void main(String args[]) throws MalformedURLException, IOException {
		java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);

		String s = "http://www.eelly.com";
		
		CheckNofollow chk = new CheckNofollow(SeoPage.downloadSeoPage(s));
		chk.check();

	}


	//涓昏皟鐢ㄥ嚱鏁�
	public void check() {
		for (Element e : seoPage.linkElements()) {
			if (!e.attr("href").startsWith("#") && !e.attr("href").startsWith("javascript"))
				probe(e);
		}
	}

	// 妫�鏌ュ崟涓狶ink Element
	public void probe(Element linkElement) {
		sd = new SeoDownloader();
		String strUrl = linkElement.attr("href");

		if (strUrl.startsWith("//"))
			strUrl = strUrl.replaceAll("//", "http://");

		if (checkRules(strUrl)) {

			// Disallowed
			if (isDisallowed(strUrl)) {
				// System.out.println("Disallowed: " + strUrl);
				robotsResultMap.put(strUrl, "Disallowed");

				// Nofollowed
				if (nofollowed(linkElement)) {
					System.out.println("OK: " + linkElement + " Disallowed And Nofollowed");
					checkResults.add("OK: " + linkElement + " Disallowed And Nofollowed");
				}
				// Followed
				else {
					System.out.println("VIOLATION: " + linkElement + " Disallowed BUT Followed");
					checkResults.add("VIOLATION: " + linkElement + " Disallowed BUT Followed");
				}

				// Allowed
			} else {
				// System.out.println("SEO: " + strUrl);
				robotsResultMap.put(strUrl, "SEO");

				// Nofollowed
				if (nofollowed(linkElement)) {
					System.out.println("VIOLATION: " + linkElement + " Allowed But Nofollowed");
					checkResults.add("VIOLATION: " + linkElement + " Allowed But Nofollowed");
				}
				// Followed
				else {
					System.out.println("OK: " + linkElement + " Allowed And Followed");
					checkResults.add("OK: " + linkElement + " Allowed And Followed");
				}
			}
		} else {
			try {
				robotsRulesMap = sd.downloadRobotsRules(strUrl,robotsRulesMap);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			probe(linkElement);
		}
	}

	public boolean nofollowed(Element input) {
		if (input.attr("rel").equals("nofollow"))
			return true;
		else
			return false;
	}

}
